<template>
  <div class="pui-slider">
    <div class="pui-slider_container">
      <div class="pui-slider_content">
        <div class="pui-slider_range" :style="`width: ${width}px;`">
          <div class="pui-slider_move" @mousedown="rangeMove"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, watch } from 'vue';
export default defineComponent({
  name: 'pui-slider',
});
</script>

<script setup lang="ts">
interface Props {
  width: number;
}

withDefaults(defineProps<Props>(), {
  width: 0,
});

const emits = defineEmits<{
  'update:width': [val: number];
  onChange: [val: number];
}>();

//滑块移动
const componentRef = reactive({
  range: 0,
  disX: 0,
});

const rangeMove = (e: any) => {
  let startX = e.clientX;
  let boxWidth = e.target.parentElement.parentElement.offsetWidth;
  document.onmousemove = (el) => {
    let endX = el.clientX;
    componentRef.disX = endX - startX;
    componentRef.range = componentRef.disX <= 0 ? 0 : componentRef.disX >= boxWidth ? boxWidth : componentRef.disX;
    emits('update:width', componentRef.range);
    e.preventDefault();
  };
  document.onmouseup = () => {
    emits('onChange', componentRef.range);
    document.onmousemove = null;
    document.onmouseup = null;
  };
};
</script>
